<template>
  <div class="" v-if="state !== 'hidden'">
    <el-form
      ref="form"
      :model="form"
      :label-width="'write' == state ? '115px' : 'auto'"
      :class="'write' == state ? 'write-form' : 'read-form'"
      :label-position="'write' == state ? 'top' : 'left'"
    >
      <div class="card-wrap flex-column justify-end card-padding">
        <div class="card-title-wrap">
          <span>车辆信息</span>
          <span></span>
        </div>

        <CarBaseInfo :form="form"></CarBaseInfo>
      </div>

      <div class="card-wrap flex-column justify-end card-padding">
        <div class="card-title-wrap">
          <span>GPS拆除信息</span>
          <span></span>
        </div>

        <el-row :gutter="30">
          <el-col :span="8">
            <el-form-item
              label="拆除设备品牌:"
              prop="gpsBrand"
              :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请选择拆除设备品牌',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.gpsBrand,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
            >
              <el-input maxlength="50"
                        v-model="form.gpsBrand"
                        clearable
                        v-if="'write' == state"
                        placeholder="请输入拆除设备品牌"
              ></el-input>
              <span v-else>{{ form.gpsBrand | filterNull }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="拆除设备类型:"
              prop="equipmentType"
            >
              <el-select filterable
                         @change="epTypeSel"
                         v-if="'write' == state"
                         v-model="form.equipmentType"
                         clearable
                         style="width: 100%"
              >
                <template
                  v-for="dict in dict.type.gps_device_type"
                >
                  <el-option
                    :label="dict.label"
                    :value="dict.value"
                    :key="dict.value"
                  ></el-option>
                </template>
              </el-select>
              <span v-else
              ><dict-tag
                :options="dict.type.gps_device_type"
                :value="form.equipmentType"
              /></span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="设备编号:" prop="equipmentNo"
                          :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择设备编号',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.equipmentNo, callback)
                                       }:{}">
              <el-input maxlength="100"
                        v-model="form.equipmentNo"
                        clearable disabled
                        v-if="'write' == state"
                        placeholder="请输入设备编号"
              ></el-input>
              <!--                            <el-select filterable-->
              <!--                                @change="equipSel"-->
              <!--                                v-if="'write' == state" v-model="form.equipmentNo" clearable style="width: 100%">-->
              <!--                                <template v-for="dict in simList">-->
              <!--                                    <el-option :label="dict.equipmentNo" :value="dict.equipmentNo" :key="dict.equipmentNo"></el-option>-->
              <!--                                </template>-->
              <!--                            </el-select>-->
              <span v-else>
                                {{ form.equipmentNo|filterNull }}

                            </span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="SIM卡号:" prop="sim"
                          :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择SIM卡号',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.sim, callback)
                                       }:{}">
              <el-input maxlength="100"
                        v-model="form.sim"
                        clearable disabled
                        v-if="'write' == state"
                        placeholder="请输入SIM卡号"
              ></el-input>
              <!--                            <el-select filterable-->
              <!--                                @change="simSel"-->
              <!--                                v-if="'write' == state" v-model="form.sim" clearable style="width: 100%">-->
              <!--                                <template v-for="dict in simList">-->
              <!--                                    <el-option :label="dict.simNo" :value="dict.simNo" :key="dict.simNo"></el-option>-->
              <!--                                </template>-->
              <!--                            </el-select>-->
              <span v-else>
                                {{ form.sim|filterNull }}

                            </span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="预约拆除时间:"
              prop="dismantleTime"
              :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请选择预约拆除时间',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.dismantleTime,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
            >
              <el-date-picker
                v-model="form.dismantleTime"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
                v-if="'write' == state"
                type="datetime"
                placeholder="请选择预约拆除时间"
              ></el-date-picker>
              <span v-else>{{
                  form.dismantleTime | filterNull
                }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="拆除费用:"
              prop="dismantlePrice"
              :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请输入拆除费用',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.dismantlePrice,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
            >
              <el-input maxlength="50"
                        v-model="form.dismantlePrice"
                        clearable
                        v-if="'write' == state"
                        oninput="if(isNaN(value)) { value = '' } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} value = value.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, 'g'), '$1')"
                        placeholder="请输入拆除费用"
              ></el-input>
              <span v-else>{{
                  form.dismantlePrice | filterNull
                }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="拆除原因:"
              prop="dismantleCause"
              :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请输入拆除原因',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.dismantleCause,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
            >
              <el-input maxlength="50"
                        v-model="form.dismantleCause"
                        clearable
                        v-if="'write' == state"
                        placeholder="请输入拆除原因"
              ></el-input>
              <span v-else>{{
                  form.dismantleCause | filterNull
                }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="拆除地点:"
              prop="dismantleAddress"
              :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请输入拆除地点',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.dismantleAddress,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
            >
              <!--                            <el-input maxlength="50"-->
              <!--                                v-model="form.dismantleAddress"-->
              <!--                                clearable-->
              <!--                                v-if="'write' == state"-->
              <!--                                placeholder="请输入拆除地点"-->
              <!--                            ></el-input>-->
              <ProvinceCityDistrict v-if="'write' == state"
                                    placeholder="请选择拆除地点" v-model="form.dismantleAddressCode"
                                    @change="citySelectionChange"></ProvinceCityDistrict>
              <span v-else>{{
                  form.dismantleAddress | filterNull
                }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="拆除详细地点:"
              prop="dismantleAddressInfo"
              :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请输入拆除详细地点',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.dismantleAddressInfo,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
            >
              <el-input maxlength="50"
                        v-model="form.dismantleAddressInfo"
                        clearable
                        v-if="'write' == state"
                        placeholder="请输入拆除详细地点"
              ></el-input>
              <span v-else>{{
                  form.dismantleAddressInfo | filterNull
                }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="拆除设备能否复用:"
              prop="isReuse"
              :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请选择',
                                          trigger: 'change',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.isReuse,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
            >
              <el-select filterable
                         v-if="'write' == state"
                         v-model="form.isReuse"
                         clearable
                         style="width: 100%"
              >
                <template v-for="dict in dict.type.gps_reuse">
                  <el-option
                    :label="dict.label"
                    :value="dict.value"
                    :key="dict.value"
                  ></el-option>
                </template>
              </el-select>
              <span v-else
              ><dict-tag
                :options="dict.type.gps_reuse"
                :value="form.isReuse"
              /></span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="现场联系人:"
              prop="sceneContacts"
              :rules="
                                'write' == state
                                    ? {
                                          required: true,
                                          message: '请输入现场联系人',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.sceneContacts,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
            >
              <el-input maxlength="50"
                        v-model="form.sceneContacts"
                        clearable
                        v-if="'write' == state"
                        placeholder="请输入现场联系人"
              ></el-input>
              <span v-else>{{
                  form.sceneContacts | filterNull
                }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="现场联系电话:"
              prop="sceneContactsTel"
              :rules="
                                'write' == state
                                    ? [{
                                          required: true,
                                          message: '请输入现场联系电话',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.sceneContactsTel,
                                                  callback
                                              ),
                                      }, { pattern:  /^1[3456789]\d{9}$/, message: '联系电话格式不正确', trigger: 'blur' }]
                                    : {}
                            "
            >
              <el-input
                v-model="form.sceneContactsTel"
                clearable maxlength="11"
                v-if="'write' == state"
                @input="value=>form.sceneContactsTel=value.replace(/[^\d]/g,'')"
                placeholder="请输入现场联系电话"
              ></el-input>
              <span v-else>{{
                  form.sceneContactsTel | filterNull
                }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="card-wrap flex-column justify-end card-padding">
        <div class="card-title-wrap">
          <span>备注</span>
          <span></span>
        </div>
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item
              label="上传照片:"
              prop="imageOss"
              style="width: 100%"
            >
              <ImageCommon
                :disabled="'write' != state"
                :up-type="2"
                info="选择附件"
                :limit="9"
                v-model="form.imageOss"
              ></ImageCommon>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="备注:"
              prop="remark"
              :rules="
                                'write' == state
                                    ? {
                                          required: 2 == form.renewFlag,
                                          message: '请输入备注',
                                          trigger: 'blur',
                                          validator: (rule, value, callback) =>
                                              validData(
                                                  rule,
                                                  form.remark,
                                                  callback
                                              ),
                                      }
                                    : {}
                            "
            >
              <el-input maxlength="500"
                        v-if="'write' == state"
                        type="textarea"
                        v-model="form.remark"
                        clearable
                        placeholder="请输入备注"
              ></el-input>
              <span v-else>{{ form.remark | filterNull }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
import moment from "moment";
import CarBaseInfo from "@/views/GPSManage/components/carBaseInfo.vue";
import {gpsSimInfo} from "@/api/gps/gpsList";
import ProvinceCityDistrict from "@/components/ProvinceCityDistrict/index.vue";

export default {
  components: {ProvinceCityDistrict, CarBaseInfo},
  dicts: ["quota_rent_type", "gps_device_type", "gps_reuse"],
  props: {
    value: {
      default: {},
    },
    state: {
      default: "write",
    },
  },
  computed: {
    form: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit("input", value);
      },
    },
  },
  watch: {
    form: {
      immediate: true,
      deep: true,
      handler(val) {
        if (this.firstEnter && val && val.carId) {
          this.firstEnter = false
          this.getSim()
        }
      }
    }
  },
  data() {
    return {
      simList: [],
      firstEnter: true,
      renewYearList: [
        {
          label: "1年",
          value: 1,
        },
        {
          label: "2年",
          value: 2,
        },
        {
          label: "3年",
          value: 3,
        },
        {
          label: "4年",
          value: 4,
        },
        {
          label: "5年",
          value: 5,
        },
      ],
    };
  },
  mounted() {
    this.$nextTick(() => {
      if ("write" == this.state) {
        this.form.imageOss = "";
      }
    });
  },
  methods: {
    epTypeSel(val) {
      if (1 == val) {
        let finds = this.simList.filter(item => item.equipmentNo.indexOf("有线") >= 0);
        this.form.sim = finds?.map(item => item.simNo).join(",");
        this.form.equipmentNo = finds?.map(item => item.equipmentNo).join(",");
      } else if (2 == val) {
        let finds = this.simList.filter(item => item.equipmentNo.indexOf("无线") >= 0);
        this.form.sim = finds?.map(item => item.simNo).join(",");
        this.form.equipmentNo = finds?.map(item => item.equipmentNo).join(",");
      } else if (3 == val) {
        let finds = this.simList.filter(item => item.equipmentNo.indexOf("有线") >= 0 || item.equipmentNo.indexOf("无线") >= 0);
        this.form.sim = finds?.map(item => item.simNo).join(",");
        this.form.equipmentNo = finds?.map(item => item.equipmentNo).join(",");
      } else {
        this.form.sim = null
        this.form.equipmentNo = null
      }
    },
    citySelectionChange(val) {
      if (val.length > 0) {
        this.form.dismantleAddressCode = val[0]?.path?.join(",") ?? ""
        this.form.dismantleAddress = val[0]?.parent?.parent?.label + val[0]?.parent?.label + val[0].label
      } else {
        this.form.dismantleAddressCode = ""
        this.form.dismantleAddress = null
      }

      this.$forceUpdate()
      this.$refs.form.validateField(["dismantleAddress"]);
      this.$nextTick(() => {
        this.$refs.form.validateField(["dismantleAddress"]);
      })

    },
    equipSel(val) {
      let find = this.simList.find(item => item.equipmentNo == val);
      if (find) {
        this.form.sim = find.simNo
      } else {
        this.form.sim = null
      }
    },
    simSel(val) {
      let find = this.simList.find(item => item.simNo == val);
      if (find) {
        this.form.equipmentNo = find.equipmentNo
      } else {
        this.form.equipmentNo = null
      }
    },
    getSim() {
      gpsSimInfo({
        carId: this.form.carId
      }).then(res => {
        // this.simList = res.data
        this.simList = res?.data[0]?.equipmentNo?.split(",")?.map((item, index) => {

          let simList = res?.data[0]?.simNo?.split(",");

          return {
            simNo: simList[index],
            equipmentNo: item,
          }

        }) ?? []
      })
    },
    renewSel(val) {
      if (this.form.renewYear && this.form.renewStartTime) {
        let endtime = moment(
          this.form.renewStartTime,
          "YYYY-MM-DD HH:mm:ss"
        )
          .add(this.form.renewYear, "year")
          .format("YYYY-MM-DD HH:mm:ss");
        this.$set(this.form, "renewEndTime", endtime);
      }
      this.$forceUpdate();
    },
    startChange(val) {
      if (this.form.renewYear && this.form.renewStartTime) {
        let endtime = moment(
          this.form.renewStartTime,
          "YYYY-MM-DD HH:mm:ss"
        )
          .add(this.form.renewYear, "year")
          .format("YYYY-MM-DD HH:mm:ss");
        this.$set(this.form, "renewEndTime", endtime);
      }
      this.$forceUpdate();
    },

    validData(rule, value, callback) {
      // console.log('aaa', rule, value, callback)
      if (rule.required && !value) {
        // this.$modal.msgError(`未填写${value}`);
        callback(new Error(rule.message));
      } else {
        callback();
      }
    },

    async valid() {
      // if(this.form.carList && this.form.carList.length>0){
      //     this.form.carIds = this.form.carList.map(item=>{
      //         return item.carId
      //     })
      //     this.form.workIds = this.form.carList.map(item=>{
      //         return item.id
      //     })
      // }else {
      //     this.form.carIds = [this.form.carId]
      //     this.form.workIds = [this.form.id]
      // }
      this.form.workId = this.form.id;

      return new Promise((resolve) => {
        if ('write' == this.state) {
          this.$refs["form"].validate(valid => {
            resolve(valid);
          });
        } else {
          resolve(true)
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}

::v-deep .read-form .el-form-item__label-wrap,
::v-deep .read-form .el-form-item__content {
  margin-left: 0 !important;
}

.el-descriptions {
  margin: 0 -15px;
}
</style>
